package com.xuecheng.base.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.List;

/**
 * ClassName: GlobalExceptionHandler
 * Package: com.xuecheng.base.exception
 * Description:
 *
 * @Author Endeavor-ZQB
 * @Create 2023/1/29 21:18
 * @Version 1.0
 */
@Slf4j
@ControllerAdvice //控制器增强
public class GlobalExceptionHandler {

    //处理XueChengPlusException异常  此类异常是程序员自动抛出的，可预知异常
    @ResponseBody //将信息返回为json格式
    @ExceptionHandler(com.xuecheng.base.exception.XueChengPlusException.class) //此方法捕获XueChengPlusException异常
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) //返回500状态码
    public com.xuecheng.base.exception.RestErrorResponse doXueChengPlusException(com.xuecheng.base.exception.XueChengPlusException e){

        log.error("捕获异常：{}",e.getErrMessage());
        e.printStackTrace();

        String errMessage = e.getErrMessage();
        return new com.xuecheng.base.exception.RestErrorResponse(errMessage);
    }

    //捕获不可预知异常 Exception
    @ResponseBody //将信息返回为json格式
    @ExceptionHandler(Exception.class) //此方法捕获Exception异常
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) //返回500状态码
    public com.xuecheng.base.exception.RestErrorResponse doException(Exception e){

        log.error("捕获异常：{}",e.getMessage());
        e.printStackTrace();
        if(e.getMessage().equals("不允许访问")){
            return new com.xuecheng.base.exception.RestErrorResponse("没有操作此功能的权限");
        }

        return new com.xuecheng.base.exception.RestErrorResponse(com.xuecheng.base.exception.CommonError.UNKOWN_ERROR.getErrMessage());
    }

    //捕获不可预知异常 MethodArgumentNotValidException
    @ResponseBody //将信息返回为json格式
    @ExceptionHandler(MethodArgumentNotValidException.class) //此方法捕获Exception异常
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) //返回500状态码
    public com.xuecheng.base.exception.RestErrorResponse doMethodArgumentNotValidException(MethodArgumentNotValidException e){

        BindingResult bindingResult = e.getBindingResult();
        //校验的错误信息
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        //收集错误
        StringBuffer errMsg = new StringBuffer();
        fieldErrors.forEach(error->{
            errMsg.append(error.getDefaultMessage()).append(",");
        });

        return new com.xuecheng.base.exception.RestErrorResponse(errMsg.toString());
    }
}
